package com.passer.simpletransfer.service.impl;

import com.google.zxing.WriterException;
import com.passer.simpletransfer.config.QrConfig;
import com.passer.simpletransfer.config.SimpleTransferProperties;
import com.passer.simpletransfer.service.SimpleTransferService;
import com.passer.simpletransfer.utils.QrCodeUtils;
import com.passer.simpletransfer.websocket.ChatWebSocketService;
import com.passer.simpletransfer.websocket.contant.WebSocketMessageType;
import com.passer.simpletransfer.websocket.vo.WebSocketMessageVo;
import com.passer.toolbox.common.file.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.File;
import java.io.IOException;

/**
 * <p>SimpleTransferService 实现类</p>
 * <p>创建时间：2023/2/10</p>
 *
 * @author hj
 */
@Slf4j
@Service
public class SimpleTransferServiceImpl implements SimpleTransferService {
    private final SimpleTransferProperties simpleTransferProperties;
    private final ConfigurableApplicationContext applicationContext;

    @Autowired
    public SimpleTransferServiceImpl(SimpleTransferProperties simpleTransferProperties, ConfigurableApplicationContext applicationContext) {
        this.simpleTransferProperties = simpleTransferProperties;
        this.applicationContext = applicationContext;
    }

    @Override
    public void clearFolder() {
        File folder = new File(simpleTransferProperties.getSaveFolderPath());
        if (folder.exists()) {
            FileUtils.deleteFolder(folder, false);
        }
    }

    @Async
    @Override
    public void closeService() {
        WebSocketMessageVo<String> messageVo = new WebSocketMessageVo<>();
        messageVo.setType(WebSocketMessageType.CLOSE);
        messageVo.setData(null);
        ChatWebSocketService.sendAllMessage(messageVo, (u, t) -> {});
        applicationContext.close();
    }

    @Override
    public String getQrCode(int width, int height, String unit) {
        QrConfig qrConfig = QrConfig.create()
                .setForeColor(new Color(7237845))
                .setBackColor(new Color(255, 255, 255, 0))
                .setRatio(8)
                .setMargin(0)
                .setWidth(width)
                .setHeight(height)
                .setUnit(unit);
        String qrCode;
        try {
            qrCode = QrCodeUtils.generateAsSvg(simpleTransferProperties.getSimpleTransferUrl(), qrConfig);
        } catch (IOException | WriterException e) {
            log.error("二维码生成失败", e);
            throw new RuntimeException("二维码生成失败");
        }
        return qrCode;
    }
}
